package com.example.springbootsfzy.controller.sunnan;
import java.io.ByteArrayOutputStream;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Base64;
import com.example.springbootsfzy.util.R;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {


    /**
     * 上传图片
     */
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile[] files) {
        // 获取当前工作目录，确保路径正确

        String path = Paths.get(System.getProperty("user.dir"), "spring-boot-sfzy", "src", "main", "resources", "static", "img").toString();


        // 检查是否有文件上传
        if (files.length == 0) {
            return R.error("上传失败，未选择文件");
        }
        // 确保目标目录存在
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();// 如果目录不存在，创建目录
            System.out.println("当前的路径:" + path);
        }
        // 遍历文件并保存
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            if (fileName == null || fileName.isEmpty()) {
                continue;  // 如果文件名为空，则跳过当前文件
            }
            // 获取文件扩展名
            String ext = fileName.substring(fileName.lastIndexOf("."));
            String newFileName = UUID.randomUUID() + ext; // 使用 UUID 生成新文件名

            try {
                // 保存文件到指定路径
                file.transferTo(new File(path + File.separator + newFileName));
            } catch (IOException e) {
                // 如果保存文件失败，返回上传失败的信息
                return R.error("上传失败：" + e.getMessage());
            }
        }
        // 返回成功信息
        return R.ok("上传成功");
    }

    /**
     * 咨询师表图片回显
     */
    @GetMapping("/download")
    public void download2(@RequestParam("fileName") String fileName, HttpServletResponse response) throws IOException {
        //是否以附件的形式下载,如果要回显图片，就把下面的一行注释或删掉
//        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        ServletOutputStream out = response.getOutputStream();
        String path = Paths.get(System.getProperty("user.dir"), "spring-boot-sfzy", "src", "main", "resources", "static", "img").toString() + File.separator + fileName;
        System.out.println("路径为:" + path);
        if (!new File(path).exists()) {
            out.write("文件不存在".getBytes());
        }

        FileInputStream in = new FileInputStream(path);
        byte[] buffer = new byte[in.available()];
        in.read(buffer);
//        String base64Encoded = Base64.getEncoder().encodeToString(buffer);
//        out.write(base64Encoded.getBytes());
        out.write(buffer);
        in.close();
        out.close();
    }

    /**
     * 首页回显
     */
    @GetMapping("/download2")
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) throws IOException {
        //是否以附件的形式下载,如果要回显图片，就把下面的一行注释或删掉
//        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        ServletOutputStream out = response.getOutputStream();
        String path = Paths.get(System.getProperty("user.dir"), "spring-boot-sfzy", "src", "main", "resources", "static", "img").toString() + File.separator + fileName;
        System.out.println("路径为:" + path);
        if (!new File(path).exists()) {
            out.write("文件不存在".getBytes());
        }

        FileInputStream in = new FileInputStream(path);
        byte[] buffer = new byte[in.available()];
        in.read(buffer);
        String base64Encoded = Base64.getEncoder().encodeToString(buffer);
        out.write(base64Encoded.getBytes());
//        out.write(buffer);
        in.close();
        out.close();
    }


    /**
     * 图片回显base64路径传值
     */
    @GetMapping("/download/{fileName}")
    public void download3(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
        // 是否以附件的形式下载，如果要回显图片，就把下面的一行注释或删掉
        // response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        ServletOutputStream out = response.getOutputStream();

        String path = Paths.get(System.getProperty("user.dir"), "spring-boot-sfzy", "src", "main", "resources", "static", "img").toString() + File.separator + fileName;
        System.out.println("路径为:" + path+fileName);
        if (!new File(path).exists()) {
            out.write("文件不存在".getBytes());
            out.close();
            return;
        }

        String ext = fileName.substring(fileName.lastIndexOf("."));
        FileInputStream in = new FileInputStream(path);
        String str = "data:image/" + ext + ";base64,";
        byte[] strBytes = str.getBytes();

        // 读取文件到buffer
        byte[] buffer = new byte[(int) new File(path).length()];
        in.read(buffer);

        // 将文件内容编码为base64
        String base64Encoded = Base64.getEncoder().encodeToString(buffer);

        // 将str和base64编码后的字符串合并
        String combined = str + base64Encoded;
        byte[] combinedBytes = combined.getBytes();

        // 写入响应流
        out.write(combinedBytes);
        in.close();
        out.close();
    }

    /**
     * 图片回显二进制路径传值
     */
    @GetMapping("/download/byte/{fileName}")
    public void download4(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
        //是否以附件的形式下载,如果要回显图片，就把下面的一行注释或删掉
//        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        ServletOutputStream out = response.getOutputStream();
        String path = Paths.get(System.getProperty("user.dir"), "spring-boot-sfzy", "src", "main", "resources", "static", "img").toString() + File.separator + fileName;
        System.out.println("路径为:" + path);
        if (!new File(path).exists()) {
            out.write("文件不存在".getBytes());
        }

        FileInputStream in = new FileInputStream(path);
        byte[] buffer = new byte[in.available()];
        in.read(buffer);
        out.write(buffer);
        in.close();
        out.close();
    }


    @PostMapping("/uploadsn")
    public R uploadsn(@RequestParam("file") MultipartFile[] files) {
        // 获取当前工作目录，确保路径正确
        String path = Paths.get(System.getProperty("user.dir"), "spring-boot-sfzy", "src", "main", "resources", "static", "img").toString();

        // 检查是否有文件上传
        if (files.length == 0) {
            return R.error("上传失败，未选择文件");
        }

        // 确保目标目录存在
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs(); // 如果目录不存在，创建目录
            System.out.println("当前的路径:" + path);
        }

        // 存储返回的文件名
        List<String> fileNames = new ArrayList<>();

        // 遍历文件并保存
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            if (fileName == null || fileName.isEmpty()) {
                continue;  // 如果文件名为空，则跳过当前文件
            }

            // 获取文件扩展名
            String ext = fileName.substring(fileName.lastIndexOf("."));
            String newFileName = UUID.randomUUID() + ext; // 使用 UUID 生成新文件名

            try {
                // 保存文件到指定路径
                file.transferTo(new File(path + File.separator + newFileName));
                fileNames.add(newFileName); // 将新文件名添加到返回列表
            } catch (IOException e) {
                // 如果保存文件失败，返回上传失败的信息
                return R.error("上传失败：" + e.getMessage());
            }
        }

        // 返回成功信息，并将新文件名返回给客户端
        return R.ok(null).put("fileNames", fileNames); // fileNames 包含所有上传成功的文件名
    }

    @PostMapping("/upload1")
    public R upload1(@RequestParam("file") MultipartFile[] files) {
        // 获取当前工作目录，确保路径正确
        String path = Paths.get(System.getProperty("user.dir"), "spring-boot-sfzy", "src", "main", "resources", "static", "img").toString();
        String newFileName = "";

        // 检查是否有文件上传
        if (files.length == 0) {
            return R.error("上传失败，未选择文件");
        }

        // 确保目标目录存在
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs(); // 如果目录不存在，创建目录
            System.out.println("当前的路径:" + path);
        }

        // 遍历文件并保存
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            if (fileName == null || fileName.isEmpty()) {
                continue;  // 如果文件名为空，则跳过当前文件
            }

            // 获取文件扩展名
            String ext = fileName.substring(fileName.lastIndexOf("."));
            newFileName = UUID.randomUUID() + ext; // 使用 UUID 生成新文件名

            try {
                // 保存文件到指定路径
                file.transferTo(new File(path + File.separator + newFileName));
            } catch (IOException e) {
                // 如果保存文件失败，返回上传失败的信息
                return R.error("上传失败：" + e.getMessage());
            }
        }

        // 返回成功信息
        return R.ok(newFileName); // 只返回一个文件名
    }
}